package com.bscc.admin.role;

import com.bscc.common.model.Menu;
import com.bscc.common.model.Role;
import com.bscc.common.model.RoleMenu;
import com.bscc.admin.menu.MenuService;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.util.ArrayList;
import java.util.List;

public class RoleService
{
    /**
     * 所有的 dao 对象也放在 Service 中
     */
    private static final Role dao = new Role().dao();
    private static final RoleMenu roleMenuDao = new RoleMenu().dao();
    private static final Menu menuDao = new Menu().dao();
    static MenuService menuService = new MenuService();

    public Page<Role> paginate(int pageNumber, int pageSize)
    {
        return dao.paginate(pageNumber, pageSize, "SELECT *", "FROM bw_role ORDER BY sort ASC");
    }

    public List<Role> roleList(boolean withoutAdmin)
    {
        return dao.find("SELECT * FROM bw_role"+(withoutAdmin?" WHERE id!=1 ":" ")+"ORDER BY sort ASC");
    }

    public Role findById(int id)
    {
        Role role = dao.findById(id);
        role.setMenuList(findRoleMenu(id));
        return role;
    }

    public void deleteById(int id)
    {
        dao.deleteById(id);
        deleteRoleMenu(id);
    }

    public void save(Role role)
    {
        List<Menu> menuList = role.getMenuList();
        role.save();
        saveRoleMenu(role, menuList);
    }

    public void update(Role role)
    {
        List<Menu> menuList = role.getMenuList();
        role.update();
        deleteRoleMenu(role.getId());
        saveRoleMenu(role, menuList);
    }

    private List<Menu> findRoleMenu(int id)
    {
        // 超级管理员获取全部菜单
        if(id == 1)
        {
            return menuService.findList();
        }

        List<RoleMenu> roleMenuList = roleMenuDao.find("SELECT * FROM bw_role_menu WHERE role_id=?", id);
        if(roleMenuList != null && roleMenuList.size() > 0)
        {
            String menuIds = "(";
            for(int i = 0; i < roleMenuList.size(); ++i)
            {
                if(i > 0)
                    menuIds += ",";
                menuIds += roleMenuList.get(i).getMenuId();
            }
            menuIds+=")";
            List<Menu> menuList = menuDao.find("SELECT * FROM bw_menu WHERE id IN "+menuIds + "ORDER BY sort");
            List<Menu> sortedList = new ArrayList<Menu>();
            menuService.sortForTree(sortedList, menuList, 0);
            return sortedList;
        }
        else
            return null;
    }

    private void deleteRoleMenu(int id)
    {
        Db.update("DELETE FROM bw_role_menu WHERE role_id=?", id);
    }

    private void saveRoleMenu(Role role,List<Menu> menuList)
    {
        if(menuList != null && menuList.size() > 0)
        {
            for(Menu m:menuList)
            {
                RoleMenu rm = new RoleMenu();
                rm.setRoleId(role.getId());
                rm.setMenuId(m.getId());
                rm.save();
            }
        }
    }
}
